import { ClipPlayingInfo } from "../core/sound_manager";
import Utils from "../core/utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SoundKit extends cc.Component {
    @property()
    clipName: string = "";
    @property()
    loopStart = 1.0;
    @property()
    loopEnd = 4.0;

    status = 0;
    maintainTime = 0;
    cpInfo: ClipPlayingInfo = null;
    playTime(time: number) {
        if (this.status == 1) {
            return;
        }
        cc.Tween.stopAllByTarget(this);
        cc.tween(this).delay(time).call(() => {
            this.stop();
        }).start();
        this.play();
    }
    play() {
        if (this.status == 1) {
            return;
        }
        if (this.cpInfo) {
            this.cpInfo.stop();
            this.cpInfo = null;
        }
        this.cpInfo = SoundManager.ins.playClip(this.clipName);
        this.status = 1;
    }

    update(dt: number) {
        if (this.status == 1) {
            this.maintainTime += dt;
        }
        else {
            this.maintainTime = 0;
        }
        if (this.cpInfo) {
            let time = this.cpInfo.time;
            if (time > this.loopEnd && this.status == 1) {
                this.cpInfo.time = this.loopStart;
            }
        }
    }

    stop() {
        if (this.status == 0) {
            return;
        }
        this.status = 0;
        if (this.cpInfo) {
            if (this.maintainTime > this.loopStart) {
                this.cpInfo.time = this.loopEnd;
            }
            else {
                this.cpInfo.stop();
                this.cpInfo = null;
            }
        }
    }


};